# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        nums = self.loop_nums(head)
        if nums == -1:
            return None
        f = l = head
        while nums > 0:
            f = f.next
            nums -= 1
        while f != l:
            f = f.next
            l = l.next
        return l
    def loop_nums(self, pHead):
        l = pHead
        f = pHead.next
        while f and f.next:
            if l == f:
                l = l.next
                count = 1
                while l != f:
                    l = l.next
                    count += 1
                return count
            l = l.next
            f = f.next.next
        return -1


l1 = ListNode(3)
l1.next = ListNode(2)
l1.next.next = ListNode(0)
l1.next.next.next = l1.next

m = Solution()
s = m.detectCycle(l1)
print(s)

